package com.letv.android.client.episode.fragment;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.episode.PlayAlbumController;
import com.letv.android.client.episode.adapter.HalfRelatedAdapter;
import com.letv.android.client.episode.callback.PlayAlbumControllerCallBack;
import com.letv.android.client.episode.parser.RelateParser;
import com.letv.android.client.episode.utils.EpisodeUtils;
import com.letv.android.client.fragment.LetvBaseFragment;
import com.letv.android.client.utils.AlbumLaunchUtils;
import com.letv.android.client.view.PublicLoadLayout;
import com.letv.android.client.webview.LetvWebViewActivity;
import com.letv.android.young.client.R;
import com.letv.core.api.LetvRequest;
import com.letv.core.api.MediaAssetApi;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.CmsBean;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.RecAlbumBean;
import com.letv.core.bean.RecommendBean;
import com.letv.core.bean.RecommendInfoListBean;
import com.letv.core.bean.RelateBean;
import com.letv.core.bean.RelateSetBean;
import com.letv.core.bean.VideoBean;
import com.letv.core.bean.VideoRelatedListBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.download.image.ImageDownloader;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyRequest.RequestManner;
import com.letv.core.network.volley.VolleyResponse.CacheResponseState;
import com.letv.core.network.volley.VolleyResponse.NetworkResponseState;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyDiskCache;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.PageIdConstant;

//import com.letv.android.client.activity.VipProductsActivity;
//import com.letv.android.client.episode.utils.LetvHightLightText;
//import com.letv.core.bean.SurroundVideoMetaData;
//import com.letv.core.utils.LetvTextUtils;
//import com.letv.download.bean.DownloadVideo;
//import com.letv.download.manager.DownloadManager;

/**
 * 新相关
 * 
 * @author yanjuli
 *
 */
public class HalfPlayRelatedFragment extends LetvBaseFragment implements OnItemClickListener,
        PlayAlbumControllerCallBack {

    // private static final String LedimVedioTagBean = HalfPlayRelatedFragment.class.getSimpleName();
    private static final String TAG = "hong";

    private PublicLoadLayout root;

    private ListView relateListView;

    private RelativeLayout pastEventRela;

    private TextView topTitle, recomPlayNum, recomUpdate;
    private ImageView recomImageView;

    /**
     * 相关数据（猜你喜欢，相关，cms）
     */
    // private VideoRelatedListBean relatedBeanArray = new VideoRelatedListBean();

    private Context mContext;

    private AlbumPlayActivity mAlbumPlayActivity;

    private HalfRelatedAdapter mHalfRelatedAdapter;

    private ImageView fiveScreenLogoImageView, playButton, likeButton;

    private PlayAlbumController playAlbumController;

    private boolean isNormalVideo;

    /**
     * 相关系列的标识
     */
    public static boolean isonRelatedVideoClick;

    /**
     * 正片推荐的标识
     */
    public static boolean isMyTopClick = false;

    /**
     * 猜你喜欢的标识
     */
    public static boolean isRecommendClick = false;

    /**
     * 用户是否可见猜你喜欢
     */
    private boolean isVisibleToUser = true;

    /**
     *{@link #setUserVisibleHint(boolean)} will call before {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     * load must be need {@link #isVisibleToUser} and {@link #isPrepared} both ture
     */
    private boolean isPrepared = true;

    private View mVipLoginView;

    private LinearLayout mBeVipRootLayout;
    private TextView mBeVipExpiringText;
    private TextView mVipActivityText;
    private TextView mBeVipRightNowBtn;
    private ImageView mTimeOutRedDotImageView;

    private LinearLayout mBeVipNewFeatureLayout;
    private TextView mNewFeaturePlayNoAds;
    private TextView mNewFeatureVipChannel;
    private TextView mNewFeatureVipMoviesLibs;
    private View mBlankPlaceholderView;

    private RelateVipView mRelateVipView;

    private boolean isVipTab = false;

    private boolean isNeedReport = true;

    /**
     * 相关数据（猜你喜欢，相关，cms） 
     */
    private VideoRelatedListBean relatedBeanArray = new VideoRelatedListBean();
    
    private Handler mHandler = new Handler(Looper.getMainLooper());

    public HalfPlayRelatedFragment() {
        LogInfo.log(TAG, "HalfPlayRelatedFragmentPlayerLibs2>>");
    }

    private void reportRelate() {
        if (!BaseTypeUtils.isListEmpty(relatedBeanArray) && isNeedReport && isVisibleToUser) {
            LogInfo.log(TAG, "relatedBeanArray.size() > 0");
            try {
                if (playAlbumController.getIsShowPayGuide()) { // 会员影片
                    LogInfo.LogStatistics("会员111 " + playAlbumController.getVideoBean());
                    StatisticsUtils.staticticsInfoPost(getActivity(), "19", "93", null, 4, null, PageIdConstant.halpPlayPage,
                            playAlbumController.cid + "", playAlbumController.getVideoBean().getPid() + "",
                            playAlbumController.vid + "", "-", "-");
                } else {
                    LogInfo.LogStatistics("相关。。。。");
                    StringBuffer sb = new StringBuffer();
                    sb.append("fl=93").append("&").append("wz=").append("4").append("&").append("pageid=")
                            .append(PageIdConstant.halpPlayPage);
                    String reid = null;
                    String area = null;
                    String bucket = null;
                    RecommendInfoListBean recomList = relatedBeanArray.getRecommendPlayerLibsList();
                    if (recomList != null && recomList.size() > 0) {
                        RecommendBean recom = recomList.get(0);
                        reid = recom.reid;
                        area = recom.area;
                        bucket = recom.bucket;
                    }
                    DataStatistics.getInstance()
                                  .sendActionInfoBigData(getActivity(), "0", "0", LetvConfig.getPcode(getActivity()), "25",
                            sb.toString(), "0", playAlbumController.cid + "",
                            playAlbumController.getVideoBean().getPid() + "", playAlbumController.vid + "",
                            LetvUtils.getUID(), reid, area, bucket, null, "-",
                            PreferencesManager.getInstance().isLogin() ? 0 : 1);
                }
                isNeedReport = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;
        //lazyLoad();
        if (!isVisibleToUser) {
            isNeedReport = true;
        }
    }

    /*
     *懒加载数据
     */
    private void lazyLoad() {
        if (isPrepared && isVisibleToUser) {
            LogInfo.log("hong","HalfPlayRelatedFragment .....");
            //数据不存在时初始化
            if (BaseTypeUtils.isListEmpty(relatedBeanArray)) {
                requestRelatedVideoTask();
            }
            reportRelate();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogInfo.log(TAG, "onCreateView >>");

        mAlbumPlayActivity = (AlbumPlayActivity) getActivity();
        playAlbumController = mAlbumPlayActivity.getPlayAlbumController();
        playAlbumController.relatedCallBack = this;

        mContext = getActivity().getApplicationContext();
        LogInfo.log("hong", "HalfPlayRelatedFragment onCreateView >> "+mContext);
        isNormalVideo = playAlbumController.isVideoNormal();
        root = PublicLoadLayout.createPage(getActivity(), R.layout.letv_detailplay_half_related_playerlibs);
        initView();
        root.loading(false);
        root.setRefreshData(new PublicLoadLayout.RefreshData() {
            @Override
            public void refreshData() {
                if (NetworkUtils.isNetworkAvailable(mContext)) {
                    requestRelatedVideoTask();
                }
            }
        });

        mRelateVipView.showPayBeVipStatus();
//        if (relatedBeanArray.size() == 0) {

//        }
        // Waiting to improve
        // loadRelateListData();

        initTopView();
        isPrepared = true;
        lazyLoad();
        return root;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mRelateVipView != null) {
            mRelateVipView.showPayBeVipStatus();
        }
    }
        
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isPrepared = false;
    }

    private long pid = -1;

    private boolean isShowTopView(AlbumNew tabAlbumInfoBean) {
        LogInfo.log(TAG, "isShowTopView isNormalVideo : " + isNormalVideo + " tabAlbumInfoBean.getPlatformVideoInfo() "
                + tabAlbumInfoBean.getPlatformVideoInfo());
        boolean res = false;
        switch (tabAlbumInfoBean.getCid()) {
            case AlbumNew.Channel.TYPE_MUSIC:
            case AlbumNew.Channel.TYPE_PE:
            case AlbumNew.Channel.TYPE_NBA:
            case AlbumNew.Channel.TYPE_HOT:
            case AlbumNew.Channel.TYPE_JOY:
            case AlbumNew.Channel.TYPE_INFORMATION:
            case AlbumNew.Channel.TYPE_FINANCIAL:
            case AlbumNew.Channel.TYPE_FASHION:
            case AlbumNew.Channel.TYPE_CAR:
            case AlbumNew.Channel.TYPE_TOURISM:
            case AlbumNew.Channel.TYPE_PATERNITY:
                res = false;
                break;
            case AlbumNew.Channel.TYPE_TVSHOW: // 综艺频道先判断relationId,再判断platformVideoInfo
                // /**
                // * 推送到移动平台总集数（合并的情况，包含所有正片和花絮等）
                // * 用于翻页
                // * */
                // private int platformVideoNum;
                //
                // /**
                // * 推送到移动平台总集数（不合并的情况，只包含正片）
                // * 用于翻页
                // * */
                // private int platformVideoInfo ;
                if (tabAlbumInfoBean.getPlatformVideoInfo() > 0 && !isNormalVideo) {
                    res = true;
                } else if (!TextUtils.isEmpty(tabAlbumInfoBean.getRelationId()) && !isNormalVideo) {
                    res = true;
                }
                break;
            default: // 直接判断platformVideoInfo
                if (tabAlbumInfoBean.getPlatformVideoInfo() > 0 && !isNormalVideo) {
                    res = true;
                }
                break;
        }
        return res;
    }

    /**
     * 区分完整是否上报,防止多次上报
     */
    private boolean topRecommendViewIsShow = false;

    private void topViewReport() {
        if (pastEventRela != null && pastEventRela.getVisibility() == View.VISIBLE) {
            if (!topRecommendViewIsShow) {
                LogInfo.LogStatistics("半屏播放器完整版浮层推荐曝光");
                StatisticsUtils.staticticsInfoPost(getActivity(), "19", "h2131", null, 0, null,
                        PageIdConstant.halpPlayPage, null, null, null, null, null);
                topRecommendViewIsShow = true;
            }
        }
    }

    private String getImageViewUrl(RecAlbumBean recAlbumBean) {
        if (!TextUtils.isEmpty(recAlbumBean.getPic400())) {
            return recAlbumBean.getPic400();
        }
        else if (!TextUtils.isEmpty(recAlbumBean.getPic320())) {
            return recAlbumBean.getPic320();
        }
        else {
            return "";
        }
    }
    
    /**
     * 初始化往期回顾
     */
    private void initTopView() {
        LogInfo.log(TAG, "initTopView playAlbumController " + playAlbumController);
        if (playAlbumController.getRecAlbumInfo() != null && pastEventRela.getVisibility() == View.GONE) { // SHOW
            RecAlbumBean recAlbumBean = playAlbumController.getRecAlbumInfo();
            pastEventRela.setVisibility(View.VISIBLE);

            try {
                topViewReport();
            } catch (Exception e) {
                e.printStackTrace();
            }

            pid = EpisodeUtils.stringToLong2(recAlbumBean.getPid());

            /*
             * 往期回顾点击播放监听
             */
            pastEventRela.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    if (view instanceof ImageView) {
                        view.setBackgroundResource(R.drawable.letv_relate_play_select);
                    }
                    AlbumLaunchUtils.launch(getActivity(), pid, 0, PlayConstant.LAUNCH_FROM_NORMAL_VIDEO_RECOMMEND,null);    //LAUNCH_FROM_RELATED
                    isMyTopClick = true;
                    // 5.7 需求 半屏播放页面-》相关正片推荐
                    LogInfo.LogStatistics("点击正片推荐");
                    StatisticsUtils.setPlayInfoRef(3);
                    StatisticsUtils.setActionProperty("h214", 1, "");
                    StatisticsUtils.staticticsInfoPost(getActivity(), "0", "h214", "1000", 1, null,
                            PageIdConstant.halpPlayPage, null, null, null, null, null);
                }
                
            });

            topTitle.setText(recAlbumBean.getNameCn());
            // modify 产品去掉
            recomUpdate.setVisibility(View.GONE);
            recomUpdate.setText(recAlbumBean.getCornerMark());

            ImageDownloader.getInstance(mContext).download(recomImageView, getImageViewUrl(recAlbumBean));

            String playCountStr = recAlbumBean.getPlayCount();

            if (!TextUtils.isEmpty(playCountStr) && !"0".equals(playCountStr)) {
                LogInfo.log(TAG, "playCountStr : " + playCountStr);
                recomPlayNum.setVisibility(View.VISIBLE);
                Drawable drawable = mContext.getResources().getDrawable(R.drawable.letv_playnum_normal);
                drawable.setBounds(0, 0, 16, 16);
                recomPlayNum.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
                recomPlayNum.setCompoundDrawablePadding(10);
                recomPlayNum.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffa1a1a1));

                long count = EpisodeUtils.stringToLong2(playCountStr.trim());

               /* recomPlayNum.setText(EpisodeUtils.getString(R.string.detail_half_player_relate_play_count,
                        EpisodeUtils.getPlayCountsToStr(count)));*/
            }
            // if (LetvSdkPlayerLibs.mContextCallback.hasCollection(pid)){
            // likeButton.setImageDrawable(null);
            // likeButton.setImageResource(R.drawable.relate_like_select);
            // }else{
            // likeButton.setImageDrawable(null);
            // likeButton.setImageResource(R.drawable.relate_like_normal);
            // }

            // likeButton.setOnClickListener(topViewClickListener);

        } else if (playAlbumController.getRecAlbumInfo() == null) { // NO SHOW
            pastEventRela.setVisibility(View.GONE);
        }
    }

    @Override
    public void notify(int state) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                handlerData();
            }
        });
    }

    @Override
    public void notify(Bundle bundle) {

    }

    private void setRelateViewSelection() {
        if (mHalfRelatedAdapter != null && playAlbumController != null
                && playAlbumController.getVideoBean() != null) {

            // smoothToSpecifyPostion((int)playAlbumController.getVideoBean().getId());
            mHalfRelatedAdapter.setCurID(playAlbumController.vid);
            mHalfRelatedAdapter.notifyDataSetChanged();

            int position = relatedBeanArray.getListViewSelectionByVid(playAlbumController.vid);

            try {
                relateListView.setSelection(position - 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void handlerData() {
        if (playAlbumController == null) {
            return;
        }
        LogInfo.log(TAG, " playAlbumController>><< " + playAlbumController == null ? " playAlbumController = null "
                : " playAlbumController.getVideoBean() " + playAlbumController.getVideoBean());

        switch (playAlbumController.relatedCallBackState) {
            case PlayAlbumControllerCallBack.STATE_NEXT:
                setRelateViewSelection();

                initTopView();

                if (mRelateVipView != null) {
                    mRelateVipView.showPayBeVipStatus();
                }

                break;
            case PlayAlbumControllerCallBack.STATE_REFRESH_DATA:
                setRelateViewSelection();
                break;
            default:
                break;
        }
    }

    private void requestRelatedVideoTask() {
        new LetvRequest<VideoRelatedListBean>(mContext, VideoRelatedListBean.class)
                .setRequestType(RequestManner.CACHE_THEN_NETROWK)
                .setCache(new VolleyDiskCache(mContext, "requestRelatedVideoTask" + playAlbumController.getCid() + playAlbumController.getVid() + playAlbumController.getPid()))
                .setParser(new RelateParser())
                .setCallback(new SimpleResponse<VideoRelatedListBean>() {

                    @Override
                    public void onNetworkResponse(VolleyRequest<VideoRelatedListBean> request,
                                                  VideoRelatedListBean result, DataHull hull, NetworkResponseState state) {
                        if (state == NetworkResponseState.SUCCESS) {
                            relatedVideoResponse(result);
                        } else if (state == NetworkResponseState.RESULT_ERROR) {
                            if (null != root)
                                root.dataError(false);
                        } else {
                            if (null != root)
                                root.netError(false);
                        }
                    }

                    @Override
                    public void onCacheResponse(VolleyRequest<VideoRelatedListBean> request,
                                                VideoRelatedListBean result, DataHull hull, CacheResponseState state) {
                        if (state == CacheResponseState.SUCCESS) {
                            relatedVideoResponse(result);
                        }
                      request.setUrl(MediaAssetApi.getInstance().getRelateUrl(String.valueOf(playAlbumController.getVid()),
                                String.valueOf(playAlbumController.getPid()), String.valueOf(playAlbumController.getCid())));
                    }

                    @Override
                    public void onErrorReport(VolleyRequest<VideoRelatedListBean> request, String errorInfo) {
                        super.onErrorReport(request, errorInfo);

                    }

                }).add();
    }

    private void relatedVideoResponse(VideoRelatedListBean result) {
        if (playAlbumController == null) {
            return;
        }
        relatedBeanArray.clear();
        relatedBeanArray.addAll(result);
//        playAlbumController.totle = result.getRecommendPlayerLibsList().getSize();

        if (relateListView.getAdapter() == null) {
            relateListView.setAdapter(mHalfRelatedAdapter);
        } 

        // 给播放器数据进行相关续播
        RecommendInfoListBean recommendList = new RecommendInfoListBean();
        recommendList.clear();
                
        if (!playAlbumController.isVideoNormal()) {
            VideoBean selfVideo = result.getSelfVideo();
            int nSize = recommendList.size();
            boolean isFindFlag = false;
            for (int i= 0; i < nSize; i++) {
                if (selfVideo.getId() == recommendList.get(i).id) {
                    isFindFlag = true;
                    break;
                }
            }
            if (!isFindFlag) {
                recommendList.add(relatedBeanArray.videoPlayerLibsToRecommendPlayerLibs(selfVideo));
            }
        }
        recommendList.addAll(result.getRecommendPlayerLibsList());
        playAlbumController.mRecommendInfoListPlayerLibs = recommendList;
        playAlbumController.relatedBeanArray = relatedBeanArray;

        // 单视频标题去掉
        if (!playAlbumController.isVideoNormal()) {
            relatedBeanArray.removeRectTitle();            
        }        

        if (mHalfRelatedAdapter != null) {
            mHalfRelatedAdapter.setIsVipTab(isVipTab);
            if (!playAlbumController.isVideoNormal()) {
                mHalfRelatedAdapter.setCurID(playAlbumController.vid);
            }
            mHalfRelatedAdapter.setIsNormalVideo(playAlbumController.isVideoNormal());
            mHalfRelatedAdapter.notifyDataSetChanged();
        }

        if (root != null) {
            root.finish();
        }

        if (playAlbumController.isNetSuccess() != playAlbumController.isCacheSuccess()) {
            reportRelate();
        }

    }

    private void initView() {
        // 相关猜你喜欢listview
        relateListView = (ListView) root.findViewById(R.id.detail_half_related_like_list);
        mHalfRelatedAdapter = new HalfRelatedAdapter(mContext, relatedBeanArray);
        addFiveScreenLogoImageView();
        relateListView.setOnItemClickListener(this);

        // 往期回顾
        pastEventRela = (RelativeLayout) root.findViewById(R.id.half_play_releted_view_layout);
        topTitle = (TextView) root.findViewById(R.id.half_play_relate_top_title);
        recomPlayNum = (TextView) root.findViewById(R.id.half_play_relate_recom_playnum);
        recomUpdate = (TextView) root.findViewById(R.id.half_play_relate_recom_update);
        recomImageView = (ImageView) root.findViewById(R.id.half_play_relate_zhengpian_imag);

        mVipLoginView = LayoutInflater.from(getActivity()).inflate(R.layout.letv_detail_half_related_top_header_view, null);
        mBeVipRootLayout = (LinearLayout) mVipLoginView.findViewById(R.id.pay_be_vip_root_layout);
        mVipActivityText = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_activity_text);
        mBeVipExpiringText = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_expiring);
        mBeVipRightNowBtn = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_right_now_btn);
        mTimeOutRedDotImageView = (ImageView) mVipLoginView.findViewById(R.id.timeout_remind_red_dot);

        mBeVipNewFeatureLayout = (LinearLayout) mVipLoginView.findViewById(R.id.pay_be_vip_feature_layout);
        mNewFeaturePlayNoAds = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_feature_play_no_ads);
        mNewFeatureVipChannel = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_feature_vip_channel);
        mNewFeatureVipMoviesLibs = (TextView) mVipLoginView.findViewById(R.id.pay_be_vip_feature_vip_movies_libs);
        mBlankPlaceholderView = mVipLoginView.findViewById(R.id.blank_placeholder_view);

        mVipActivityText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferencesManager.getInstance().isLogin()
                        && PreferencesManager.getInstance().isVip()) {
                    if (!TextUtils.isEmpty(mDefaultTextVipActivityTextUrl)) {
                        String webViewUrl = BaseTypeUtils.checkUrl(mDefaultTextVipActivityTextUrl);
                        LetvWebViewActivity.launch(mAlbumPlayActivity,
                                webViewUrl, "");
                    } else {
                       /* VipProductsActivity.launch(mAlbumPlayActivity, mContext
                                        .getString(R.string.pim_vip_recharge),
                                PreferencesManager.getInstance()
                                        .isSViP());*/
                    }
                } else {
                    if (!TextUtils.isEmpty(mDefaultTextActivityTextNonVipUrl)) {
                        String webViewUrl = BaseTypeUtils.checkUrl(mDefaultTextActivityTextNonVipUrl);
                        LetvWebViewActivity.launch(mAlbumPlayActivity,
                                webViewUrl, "");
                    } else {
                        //VipProductsActivity.launch(mAlbumPlayActivity, mContext.getString(R.string.pim_vip_good_title));
                    }
                }
            }
        });

        mBeVipRightNowBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferencesManager.getInstance().isLogin()
                        && PreferencesManager.getInstance().isVip()) {
/*                    VipProductsActivity.launch(mAlbumPlayActivity, mContext
                                    .getString(R.string.pim_vip_recharge),
                            PreferencesManager.getInstance().isSViP());*/
                    // 5.7会员身份访问半屏播放页-续费会员
                    LogInfo.log("glh", "续费会员");
                    StatisticsUtils.staticticsInfoPost(mContext, "0", "m01",
                            null, 2, null,
                            PageIdConstant.halpPlayPage, null, null,
                            null, null, null);
                } else {
                    // 进入普通会员购买收银台
                 /*   VipProductsActivity.launch(mAlbumPlayActivity, mContext
                            .getString(R.string.pim_vip_good_title));*/
                    // 5.7非会员访问半屏播放页时-立即开通会员
                    LogInfo.log("glh", "立即开通会员");
                    StatisticsUtils.staticticsInfoPost(mContext, "0", "m01",
                            null, 1, null,
                            PageIdConstant.halpPlayPage, null, null,
                            null, null, null);
                }
            }
        });

        mRelateVipView = new RelateVipView();
    }

    // 非会员身份访问半屏播放页时(含登陆非会员与非登录用户)
    // private String mDefaultTextActivityTextNonVipTitle = ""; // for non vip
    // webview title
    private String mDefaultTextActivityTextNonVipUrl = "";
    private String mDefaultTextActivityTextNonVip = "";
    private String mDefaultTextPlayNoAds;
    private String mDefaultTextVipChannel;
    private String mDefaultTextVipMovieLibs;

    // 会员身份访问半屏播放页时
    // private String mDefaultTextVipActivityTextTitle = ""; // for vip webview
    // title
    private String mDefaultTextVipActivityTextUrl = "";
    private String mDefaultTextVipActivityText = "";
    private String mDefaultTextVipExpire;
    private String mDefaultTextVipExpireToday;

    private void loadDefaultConfigText() {
        // 非会员身份访问半屏播放页时(含登陆非会员与非登录用户)
        // mDefaultTextActivityTextNonVipTitle = LetvTools.getTextFromServer("10086", "");
      /*  try {
            mDefaultTextActivityTextNonVipUrl = LetvTools.getTextTitleFromServer("10086", "");
            mDefaultTextActivityTextNonVip = LetvTools.getTextFromServer("10086", "");
            mDefaultTextPlayNoAds = LetvTools.getTextFromServer("10087", ""); // getResources().getString(R.string.pay_be_vip_feature_play_no_ads)
            mDefaultTextVipChannel = LetvTools.getTextFromServer("10088", ""); // getResources().getString(R.string.pay_be_vip_feature_vip_channel)
            mDefaultTextVipMovieLibs = LetvTools.getTextFromServer("10089", "");// getResources().getString(R.string.pay_be_vip_feature_vip_movies_libs)

            // 会员身份访问半屏播放页时
            // mDefaultTextVipActivityTextTitle = LetvTools.getTextFromServer("10090", "");
            mDefaultTextVipActivityTextUrl = LetvTools.getTextTitleFromServer("10090", "");
            mDefaultTextVipActivityText = LetvTools.getTextFromServer("10090", "");
            mDefaultTextVipExpire = LetvTools.getTextFromServer("10091",
                    getResources().getString(R.string.pay_be_vip_expiring));
            mDefaultTextVipExpireToday = LetvTools.getTextFromServer("10104",
                    getResources().getString(R.string.pay_be_vip_expiring_today));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 会员频道 会员view 处理
     * 
     * @author yanjuli
     *
     */
    private class RelateVipView {

        /*
         * 只有在付费影片是显示付费引导图
         */
        public void showPayBeVipStatus() {
            // 当播放影片为付费影片时
            if (playAlbumController != null && playAlbumController.getIsShowPayGuide()) {
                loadDefaultConfigText();
                isVipTab = true;
                boolean isLoginFlag = PreferencesManager.getInstance().isLogin();
                if (!isLoginFlag || (isLoginFlag && !PreferencesManager.getInstance().isVip())) {
                    showPayBeVipRightNow();
                } else {
                    showPayBeVipContinue();
                    getDiscount();
                }

                try {
                    if (mVipLoginView != null) {
                        relateListView.removeHeaderView(mVipLoginView);
                    }
                    relateListView.addHeaderView(mVipLoginView, null, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                isVipTab = false;
                if (mVipLoginView != null) {
                    relateListView.removeHeaderView(mVipLoginView);
                }
            }
        }

        /**
         * 得到折扣
         */
        private void getDiscount() {
          /*  String discount = PreferencesManager.getInstance().getContinueDiscount(
                    PreferencesManager.getInstance().getUserId());
            long lastdays = PreferencesManager.getInstance().getLastdays();
            long chkvipday = PreferencesManager.getInstance().getChkvipday();
            boolean isVip = PreferencesManager.getInstance().isVip();
            if (Math.abs(lastdays) <= chkvipday) {// 续费提示期内有优惠的情况下只显示“会员续费减[X]元”；续费提示期内没有优惠的情况下只显示“会员续费”
                if ("0".equals(discount)) {
                    mBeVipRightNowBtn.setText(R.string.pay_be_vip_continue);
                } else {
                    discount = String.format(getString(R.string.pim_be_vip_dis), discount);
                    mBeVipRightNowBtn.setText(discount);
                }
                mTimeOutRedDotImageView.setVisibility(View.VISIBLE);
                mTimeOutRedDotImageView.bringToFront();
            } else {// 非续费提示期内的非会员只显示“开通会员”；非续费提示期内的会员只显示“会员续费”
                mTimeOutRedDotImageView.setVisibility(View.GONE);
                if (!isVip) {
                    discount = String.format(getString(R.string.pim_be_vip));
                } else {

                    if (!"0".equals(discount)) {
                        discount = String.format(getString(R.string.pim_be_vip_dis), discount);
                    } else {

                        discount = String.format(getString(R.string.pay_be_vip_continue));
                    }
                }
                mBeVipRightNowBtn.setText(discount);
            }*/
        }

        /*
         * 会员身份访问半屏播放页时
         */
        private void showPayBeVipContinue() {
            if (!TextUtils.isEmpty(mDefaultTextVipActivityText)) {
                mVipActivityText.setText(mDefaultTextVipActivityText);
                mVipActivityText.setVisibility(View.VISIBLE);
            } else {
                mVipActivityText.setVisibility(View.GONE);
            }

            String expiringText = "";
            if (!TextUtils.isEmpty(mDefaultTextVipExpire)) {
                expiringText = mDefaultTextVipExpire;
            } else {
            //    expiringText = getString(R.string.pay_be_vip_expiring);
            }

            // 是否在需要检查vip过期的时间内
            long lastdays = PreferencesManager.getInstance().getLastdays(); // 单位时间为秒
            long chkvipday = PreferencesManager.getInstance().getChkvipday(); // 单位时间为秒
            if (lastdays >= 0 && lastdays <= chkvipday) {
                long currentDateTimeValue = PreferencesManager.getInstance().getCacheCancelTime() - lastdays * 1000;
                long lastCacheDateTimeValue = PreferencesManager.getInstance().getCacheCancelTime();
                String currentDateTime = StringUtils.timeString(currentDateTimeValue);
                String lastCancelDate = StringUtils.timeString(lastCacheDateTimeValue);
                // int currentDateTimeInt = (int)(currentDateTimeValue / LetvConstant.OVERDUE_TIME_IN_SECS);
                // int lastCacheDateTimeInt = (int)(lastCacheDateTimeValue / LetvConstant.OVERDUE_TIME_IN_SECS);
                // int lastIntegerDays = (int)((lastCacheDateTimeValue - currentDateTimeValue) /
                // LetvConstant.OVERDUE_TIME_IN_SECS); //获取相差的天数
                int lastIntegerDays = EpisodeUtils.getMinusDaysBetweenTwoDate(lastCacheDateTimeValue,
                        currentDateTimeValue);
                /*if (lastIntegerDays >= 0 && lastIntegerDays < 2) {
                    if (currentDateTime.equals(lastCancelDate)) {
                        mBeVipExpiringText.setText(LetvHightLightText.highlightParamText(mDefaultTextVipExpireToday,
                                "今天", getResources().getColor(R.color.letv_color_ff0000), false));
                    } else {
                        mBeVipExpiringText.setText(LetvHightLightText.highlightParamTextOffsetRightOne(expiringText,
                                lastIntegerDays, getResources().getColor(R.color.letv_color_ff0000)));
                    }
                } else {
                    mBeVipExpiringText.setText(LetvHightLightText.highlightParamTextOffsetRightOne(expiringText,
                            lastIntegerDays, getResources().getColor(R.color.letv_color_ff0000)));
                }*/
                mBeVipExpiringText.setVisibility(View.VISIBLE);
            } else {
                mBeVipExpiringText.setVisibility(View.GONE);
            }

           // mBeVipRightNowBtn.setText(getString(R.string.pay_be_vip_continue));
            mBeVipNewFeatureLayout.setVisibility(View.GONE);
        }

        /*
         * 非会员身份访问半屏播放页时(含登陆非会员与非登录用户)
         */
        private void showPayBeVipRightNow() {
            if (!TextUtils.isEmpty(mDefaultTextActivityTextNonVip)) {
                mVipActivityText.setText(mDefaultTextActivityTextNonVip);
                mVipActivityText.setVisibility(View.VISIBLE);
            } else {
                mVipActivityText.setVisibility(View.GONE);
            }
            mBeVipExpiringText.setVisibility(View.GONE);
           // mBeVipRightNowBtn.setText(getString(R.string.pim_be_vip));
            // The blow is vip feature
            // play no ads
            if (!TextUtils.isEmpty(mDefaultTextPlayNoAds)) {
                mNewFeaturePlayNoAds.setText(mDefaultTextPlayNoAds.replace("\\n", "\n"));
            }
            // vip channel
            if (!TextUtils.isEmpty(mDefaultTextVipChannel)) {
                mNewFeatureVipChannel.setText(mDefaultTextVipChannel.replace("\\n", "\n"));
            }
            // movie libs
            if (!TextUtils.isEmpty(mDefaultTextVipMovieLibs)) {
                mNewFeatureVipMoviesLibs.setText(mDefaultTextVipMovieLibs.replace("\\n", "\n"));
            }

            mBeVipNewFeatureLayout.setVisibility(View.VISIBLE);
        }
    }

    private void addFiveScreenLogoImageView() {
        if (fiveScreenLogoImageView == null) {
            fiveScreenLogoImageView = new ImageView(getActivity());
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            fiveScreenLogoImageView.setLayoutParams(params);
            fiveScreenLogoImageView.setPadding(0, UIsUtils.zoomWidth(mContext,10), 0, UIsUtils.zoomWidth(mContext,10));
            fiveScreenLogoImageView.setImageResource(R.drawable.letv_home_foot_image);
            fiveScreenLogoImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        }
        if (fiveScreenLogoImageView != null) {
            relateListView.removeFooterView(fiveScreenLogoImageView);
        }
        relateListView.addFooterView(fiveScreenLogoImageView, null, false);

       /* boolean hasAttendance = LetvTools.getTextTitleFromServer("80000", "0").equals("1");
        if (hasAttendance) {
            fiveScreenLogoImageView.setVisibility(View.VISIBLE);
        } else {
            fiveScreenLogoImageView.setVisibility(View.GONE);
        }*/
    }

    private TabsFragment getTabsFragment() {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        if (fm != null) {
            TabsFragment tabsFragment = (TabsFragment) fm.findFragmentByTag(TabsFragment.class.getSimpleName());
            if (tabsFragment != null) {
                return tabsFragment;
            }
        }
        return null;
    }
    
    /*
     * 更新底部工具栏显示状态
     */
    private void refreshBottomBarStatus() {
        if (getTabsFragment() != null) {
//            getTabsFragment().refreshBottomBarStatus();
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 防止快速点击
     /*   if (!LetvUtils.checkClickEvent(500)) {
            return;
        }*/

        RelateSetBean relatedBean = null;
        try {
            if (playAlbumController.getIsShowPayGuide()) {
                relatedBean = relatedBeanArray.get(position - 1);
            } else {
                relatedBean = relatedBeanArray.get(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        switch (relatedBean.type) {
            case VideoRelatedListBean.SELF_VIDEO_TYPE:
                if (relatedBean.tabVideoInfoBean != null) {
                    if (relatedBean.tabVideoInfoBean.getId() != playAlbumController.vid) {
                        onRelatedNowVideoClick(relatedBean.tabVideoInfoBean);
                        refreshBottomBarStatus();
                    }
                }
                break;
            case VideoRelatedListBean.CMS_CONTENT_TYPE:
                onRelatedCMSdClick(relatedBean.cms);
                break;
            case VideoRelatedListBean.RECT_CONTENT_TYPE:
                if (playAlbumController.vid != relatedBean.rect.id) {
                    if (relatedBean.rect != null) {
                        long curID = relatedBean.rect.id;
                        mHalfRelatedAdapter.setCurID(curID);
                        mHalfRelatedAdapter.notifyDataSetChanged();
                    }

                    onRelatedRecommendClick(relatedBean.rect, position);                
                    refreshBottomBarStatus();
                }                
                break;
            case VideoRelatedListBean.RELATE_CONTENT_TYPE:
                onRelatedVideoClick(relatedBean.relate);
                playAlbumController.isRefreshRelateDataAfterRequestPlayUrl = true;
                break;
            default:
                break;
        }

        if (!playAlbumController.isVideoNormal()) {            
            if (relateListView != null) {
                try {
                    relateListView.setSelection(position - 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 相关视频点击
     * 
     * @param relate
     */
    private void onRelatedVideoClick(RelateBean relate) {
        // 无vid 暂时传“0”
        AlbumLaunchUtils.launch(getActivity(), relate.stringToLong(relate.pid), 0, PlayConstant.LAUNCH_FROM_RELATED,null);
        isonRelatedVideoClick = true;
        // 5.7需求 相关系列 点击
        LogInfo.LogStatistics("相关系列:name=" + relate.nameCn);
        StatisticsUtils.setActionProperty("h214", 3, "");
        StatisticsUtils.setPlayInfoRef(4);
        StatisticsUtils.staticticsInfoPost(getActivity(), "0", "h214", null, 3, null, PageIdConstant.halpPlayPage,
                null, null, null, null, null);
    }

    /**
     * cms 点击
     */

    private void onRelatedCMSdClick(CmsBean cms) {
        if (getActivity() == null || cms == null) {
            return;
        }

        //SurroundVideoMetaData newCms = LetvTools.copyBean(cms, SurroundVideoMetaData.class);

       /* HomeMetaData homeMetaData = LetvTextUtils.replaceObjectModel(newCms);
        UIControllerUtils.gotoActivity(getActivity(), homeMetaData, -1, -1);*/
    }

    private void onRelatedNowVideoClick(VideoBean videoPlayerLibs) {
        if (videoPlayerLibs.getType() == 1) {
            AlbumLaunchUtils.launch(getActivity(), videoPlayerLibs.getPid(), videoPlayerLibs.getId(),
                    PlayConstant.LAUNCH_FROM_RELATED,null);
        } else if (playAlbumController != null && playAlbumController.getVideoBean() != null
                && videoPlayerLibs.getId() != playAlbumController.getVideoBean().getId()) {
            playAlbumController.play(videoPlayerLibs);
            mHalfRelatedAdapter.setCurID(videoPlayerLibs.getId());
            mHalfRelatedAdapter.notifyDataSetChanged();
        } 
        else {
          /*  DownloadVideo dbBean = DownloadManager.getDownloadedVideoData(String.valueOf(videoPlayerLibs.getId()));
            boolean hasDownload = (dbBean != null) && dbBean.state == DownloadVideo.DownloadState.FINISHED_STATE;
            if (hasDownload) {
                playAlbumController.play(videoPlayerLibs);
                mHalfRelatedAdapter.setCurID(videoPlayerLibs.getId());
                mHalfRelatedAdapter.notifyDataSetChanged();
            }*/
        }
    }

    private void onRelatedRecommendClick(RecommendBean rect, int position) {
       /* if (rect == null || playAlbumController == null || playAlbumController.getVideoBean() == null
                || rect.id == playAlbumController.getVideoBean().getId()) {
            DownloadVideo dbBean = DownloadManager.getDownloadedVideoData(String.valueOf(rect.id));
            boolean hasDownload = (dbBean != null) && dbBean.state == DownloadVideo.DownloadState.FINISHED_STATE;
            if (!hasDownload) {
                return;
            }
        }*/

        // //add xulong xian根据返回类型区分是专辑还是单视频
        if (rect.type == 1) {
            AlbumLaunchUtils.launch(getActivity(), rect.pid, rect.id, PlayConstant.LAUNCH_FROM_RELATED,null);
        } else {
            if (!isNormalVideo && playAlbumController != null) {
                VideoBean video = new VideoBean();
                video.setCid(rect.cid);
                video.setVid(rect.id);
                video.setNameCn(rect.title);
                playAlbumController.play(video);
            } else {
                AlbumLaunchUtils.launch(getActivity(), rect.pid, rect.id, PlayConstant.LAUNCH_FROM_RELATED,null);
            }
        }
        // 5.6需求 猜你喜欢的点击
        StringBuffer sb = new StringBuffer();
        sb.append("fl=h214").append("&").append("wz=4").append("&").append("pageid=")
                .append(PageIdConstant.halpPlayPage);
        DataStatistics.getInstance()
                      .sendActionInfoBigData(getActivity(), "0", "0", LetvConfig.getPcode(getActivity()), "17",
                sb.toString(), "0", rect.cid + "", rect.pid + "", rect.id + "", LetvUtils.getUID(),
                rect.reid == null ? "-" : rect.reid, rect.area == null ? "-" : rect.area,
                rect.bucket == null ? "-" : rect.bucket, (position) + "", "-",
                PreferencesManager.getInstance().isLogin() ? 0 : 1);
        isRecommendClick = true;
        StatisticsUtils.setPlayInfoRef(1);
        LogInfo.LogStatistics("猜你喜欢点击:pos=" + position + "name=" + (rect.type == 1 ? rect.pidname : rect.title)
                + ",area=" + rect.area + ",reid=" + rect.reid + ",bucket=" + rect.bucket);
    }

    @Override
    public String getTagName() {
        return HalfPlayRelatedFragment.class.getSimpleName();
    }

    @Override
    public int getContainerId() {
        return 0;
    }

}
